import axios from 'axios'
import { Message } from '@/components'
const $axios = axios.create({ 
    baseURL: process.env.BASE_URL,
    headers: {
       "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    timeout: 10000, 
});

$axios.interceptors.request.use(config => {
    const token=localStorage.getItem('token')
    if(token){
        config.headers.token = token;
    }
    return config;
});

$axios.interceptors.response.use((response)=>{
    const res = response.data;
    if(res.code === 0){

    }else if(res.code === 1000){
        Message.warn('用户未登录')
        window.location.href = '/#/login';
    }else{
        Message.error(res.message)
    }
    return res;
},(err)=>{
    console.error('err',err)
    Message.error('网络请求异常，请稍后重试!')
});

const isDev=process.env.NODE_ENV==='development'

export default{
    post(url:string,data:object){
        return $axios({
            method:'post',
            url:isDev?url+'.json':url,
            data:Object.assign({},data,{token:localStorage.getItem('token')})
        })
    },
    get(url:string,params?:object){
        return $axios({
            method:'get',
            url:isDev?url+'.json':url,
            params
        })
    },
    upload(url:string,fb:FormData){
        return $axios({
            method:'post',
            url,
            data:fb,
            headers: {'Content-Type': 'multipart/form-data'},
        })
    }
}